import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'

import { uuid } from '@/utils/YunMaiUtils'

import './index.less'

interface WordHScrollProps {
  children: React.ReactElement
  wordSeparateGap?: number
  fontSize?: string
}

const WordHScroll: React.FC<WordHScrollProps> = (props) => {
  const { children, wordSeparateGap = 8, fontSize = '12px' } = props

  const wordRef = useRef<HTMLParagraphElement>(null)
  const animationIdRef = useRef<any>()
  const scrollBlockRef = useRef<HTMLDivElement>(null)
  const scrollWordRef = useRef<HTMLDivElement>(null)
  const [portalDetail, setPortalDetail] = useState<{
    domId: string
    children: React.ReactElement
    container: HTMLDivElement
  }>()

  const [needScroll, setNeedScroll] = useState<boolean>(false)
  const [wordWidth, setWordWidth] = useState<number>(0)
  const timeoutIdRef = useRef<any>()

  function wordScroll() {
    // console.log('--scrollBlockRef.current--scrollWordRef.current--:', scrollBlockRef.current, scrollWordRef.current)
    if (scrollBlockRef.current && scrollWordRef.current) {
      const { scrollLeft: blockScrollLeft } = scrollBlockRef.current
      const { clientWidth: wordClientWidth } = scrollWordRef.current
      if (blockScrollLeft >= wordClientWidth) {
        //div.scroll-horizontal-word刚好向左滑出div.scroll-horizontal-block框外
        scrollBlockRef.current.scrollLeft -= wordClientWidth // 0
        if (animationIdRef.current) {
          cancelAnimationFrame(animationIdRef.current)
          timeoutIdRef.current = setTimeout(() => {
            //滑到头了暂停2s再开始
            wordScroll()
          }, 2000)
          return
        }
      } else {
        scrollBlockRef.current.scrollLeft += 1
      }
    }
    animationIdRef.current = requestAnimationFrame(wordScroll)
  }

  useLayoutEffect(() => {
    if (!children) return
    // console.log('--children--', children.props.children)

    const domId = uuid()
    const divDom = document.createElement('div')
    divDom.style.visibility = 'hidden'
    divDom.style.display = 'inline-block'
    // NOTE: 需要设置字体大小，否则获取的宽度不准确
    divDom.style.fontSize = fontSize
    divDom.id = domId
    document.body.appendChild(divDom)

    const portalDetail = {
      domId,
      children,
      container: divDom
    }

    setPortalDetail(portalDetail)
  }, [])

  useEffect(() => {
    if (!portalDetail || !wordRef.current) return

    timeoutIdRef.current = setTimeout(() => {
      const { domId } = portalDetail
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current)
      }
      // console.log('--portalDetail.children.props.children--:', portalDetail.children.props.children);
      const divDom = document.getElementById(domId)
      if (!divDom) {
        console.error('--WordHScroll--临时divDom不存在--')
        return
      }
      const currWordWidth = divDom.clientWidth
      setWordWidth(currWordWidth)
      document.body.removeChild(divDom)
      const wordParent = wordRef.current!.parentNode as Element
      if (!wordParent) {
        throw new Error('WordHScroll组件必须要有一个块级父节点')
      }
      // console.log("currWordWidth--wordParent.clientWidth", currWordWidth, wordParent.clientWidth)
      if (currWordWidth > wordParent.clientWidth) {
        setNeedScroll(true)
        wordScroll()
      }
    }, 2000)
    return () => {
      // setNeedScroll(false)
      // console.log('--destroy--')
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current)
      }
      if (animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current)
      }
    }
  }, [portalDetail])

  return !needScroll ? (
    <>
      {portalDetail &&
        createPortal(
          portalDetail.children,
          portalDetail.container,
          portalDetail.domId
        )}
      <p ref={wordRef} style={{ display: 'inline-block' }}>
        {children}
      </p>
    </>
  ) : (
    <div className="scroll-horizontal-block" ref={scrollBlockRef}>
      <div
        className="scroll-horizontal-content"
        style={{ width: (wordWidth + wordSeparateGap) * 2 + 'px' }}
      >
        <div
          className="scroll-horizontal-word"
          ref={scrollWordRef}
          style={{ paddingRight: `${wordSeparateGap}px` }}
        >
          {children}
        </div>
        <div
          className="scroll-horizontal-word"
          style={{ paddingRight: `${wordSeparateGap}px` }}
        >
          {children}
        </div>
      </div>
    </div>
  )
}

export default memo(WordHScroll)
